﻿// CapturedFrame
// 
// Wrapper for captured webcam frame
// 
// FLMScan - Featured by FabLab Munich

using System;
using System.Drawing;
using FLMScan.Geometry;
using System.Collections.Generic;
using FLMScan.OpenCV;

namespace FLMScan.Capture
{
    class CapturedFrame : IDisposable
    {
        private bool isDisposed = false;

        private IplImage frame;
        private Bitmap bitmap;

        public CapturedFrame(Bitmap image)
        {
            frame = CaptureWrapperOpenCV.ToIplImage(image, false);
            bitmap = image;            
        }

        public CapturedFrame(IplImage image)
        {
            if (image.ptr != IntPtr.Zero)
            {
                /* allocate all the buffers */
                frame = CaptureWrapperOpenCV.CvCreateImage(CaptureWrapperOpenCV.CvGetSize(ref image), 8, 3);
                frame.origin = image.origin;

                CaptureWrapperOpenCV.CvCopy(ref image, ref frame);                
            }
        }

        public IplImage Frame
        {
            get{ return frame; }
        }

        public Bitmap Bitmap
        {
            get { return bitmap; }
            set { bitmap = value; }
        }

        public bool IsValidFrame()
        {
            return (frame.ptr != null);
        }

        public void MarkFeatures(List<FlmPoint> imagePlanePoints)
        {
            CaptureWrapperOpenCV.MarkFeatures(ref frame, imagePlanePoints);

            if (IsValidFrame())
            {
                Bitmap = CaptureWrapperOpenCV.ToBitmap(frame, false);
            }
        }
        
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool isDisposing)
        {
            if (isDisposed)
                return;

            if (isDisposing)
            {
                isDisposed = true;

                CaptureWrapperOpenCV.CvReleaseImage(ref frame);
            }
        }   
    }
}
